package com.xsx.web;

import com.xsx.pojo.User;
import com.xsx.service.UserService;
import com.xsx.service.impl.UserServiceImpl;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 注册用户
 */
public class RegistServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//    1.获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");
        //2.检查 验证码是否正确 写死 adcde
        if ("abc".equalsIgnoreCase(code)) {
//            3.检查用户名是否可用
            if (!userService.existsUserName(username)) {
                userService.registUser(new User(null, username, password, email));
                resp.sendRedirect("http://localhost:8088/book/pages/user/regist_succes.html");
            } else {
                System.out.println("用户[" + username + "]已存在");
                resp.sendRedirect("http://localhost:8088/book/pages/user/regist.html");
            }
        } else {
            System.out.println("验证码[" + code + "]错误!");
            //重定向 回注册页面
            resp.sendRedirect("http://localhost:8088/book/pages/user/regist.html");
            //html表单用了绝对路径 这就不能用 请求转发了
//            req.getRequestDispatcher("/pages/user/regist.html").forward(req,resp);
        }

        System.out.println("调用资源成功");

    }
}
